package xiaopiya.robot.handler.weather;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 基于tq121天气数据的天气服务实现
 * 
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class Tq121WeatherService implements IWeatherService
{
	private final static Log LOG = LogFactory.getLog(Tq121WeatherService.class);

	private final static String WEATCHER_URL = "http://weather.tq121.com.cn/mapanel/index1.php?city=";

	/*
	 * (non-Javadoc)
	 * 
	 * @see xiaopiya.robot.handler.weather.IWeatherService#getWeather(java.lang.String)
	 */
	public String getWeather(String city)
	{
		try
		{
			HttpClientParams clientParams = new HttpClientParams();
			clientParams.setConnectionManagerTimeout(1000);
			clientParams.setSoTimeout(1000);
			HttpClient httpclient = new HttpClient(clientParams);
			GetMethod method = new GetMethod(WEATCHER_URL
					+ URLEncoder.encode(city, "gb2312"));

			httpclient.executeMethod(method);

			String response = new String(method.getResponseBody(), "gb2312");

			Tq121Weather weather = new Tq121Weather(response);
			if (LOG.isInfoEnabled())
			{
				LOG
						.info("find weather[" + weather + "] for city[" + city
								+ "]");
			}
			return weather.toString();
		} catch (UnsupportedEncodingException e)
		{
			if (LOG.isInfoEnabled())
			{
				LOG.info("UnsupportedEncodingException", e);
			}
			return null;
		} catch (Throwable t)
		{
			return "错误的城市或找不到该城市的天气或连接天气预报服务器出错";
		}
	}
}
